﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;

namespace ProjectSem3.Admin
{
    public partial class Default : System.Web.UI.Page
    {
        private dataDataContext dc = new dataDataContext();
        
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Request.Cookies.AllKeys.Contains("userinfo"))
                {
                    HttpCookie ckuser = Request.Cookies["userinfo"];
                    textfield.Text= ckuser["name"];
                    textfield2.Text= ckuser["pass"];
                }
            }
        }

       
    

        protected void ButtonLogin_Click(object sender, EventArgs e)
        {
            Employee emp = null;
            string pwd = FormsAuthentication.HashPasswordForStoringInConfigFile(textfield2.Text, "sha1");
            try
            {
                emp = dc.Employees.Single(em => em.Username.Equals(textfield.Text) && em.Password.Equals(pwd));

                Session["user"] = emp;
                if (checkbox.Checked)
                {
                    HttpCookie ckuser = new HttpCookie("userinfo");

                    ckuser.Expires = DateTime.Now.AddDays(1);
                    ckuser["name"] = emp.Username;
                    ckuser["pass"] = textfield2.Text;
                    Response.Cookies.Add(ckuser);
                }
                else
                {
                    if (Request.Cookies.AllKeys.Contains("userinfo"))
                    {
                        HttpCookie ckuser = new HttpCookie("userinfo");
                        ckuser.Expires = DateTime.Now.AddDays(-1);
                        Response.Cookies.Add(ckuser);
                    }
                }
                if (emp!=null)
                {
                    Response.Redirect("Index.aspx");
                }
                else
                    lblerror.InnerHtml = "Username or password is incorrect, please try again!";
            }
            catch (Exception)
            {
                lblerror.InnerHtml ="Login faild";
            }
         
        }
    }
}